<template>
  <div class="hs-tree-wrapper">
    <el-input
      v-model="filterText"
      placeholder="搜索HS编码或名称"
      clearable
      @input="onFilter"
      class="filter-input"
    />
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="defaultProps"
      node-key="code"
      show-checkbox
      highlight-current
      class="hs-tree"
      :expand-on-click-node="false"
      :check-strictly="true"
    />
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { hsData } from '../../utils/GlobalhsData.js'; // 替换为实际路径

const props = defineProps({
  rawHs: {
    type: Object,
    default: () => hsData.hs246
  }
});

const treeRef = ref(null);
const filterText = ref('');
const treeData = ref([]);
const rawTree = ref([]);
const defaultProps = { children: 'children', label: 'label' };

// code 映射：code -> node，code -> parentCode
const nodeMap = new Map();
const parentMap = new Map();

/**
 * 构建原始树、辅助映射
 */
function buildTree() {
  nodeMap.clear();
  parentMap.clear();

  function build(nodes, parentCode = null) {
    return Object.values(nodes).map(item => {
      const node = {
        code: item.code,
        label: item.label,
        children: item.children ? build(item.children, item.code) : undefined
      };
      nodeMap.set(item.code, node);
      parentMap.set(item.code, parentCode);
      return node;
    });
  }

  rawTree.value = build(props.rawHs);
  treeData.value = rawTree.value;
}

buildTree();

// 监听数据变更
watch(() => props.rawHs, () => buildTree());

/**
 * 搜索并自动展开匹配路径
 */
function onFilter() {
  const keyword = filterText.value.trim().toLowerCase();

  if (!keyword) {
    treeData.value = rawTree.value;
    nextTick(() => treeRef.value?.collapseAll());
    return;
  }

  // 找到所有匹配的 code
  const matchedCodes = [];
  nodeMap.forEach((node, code) => {
    if (
      node.label.toLowerCase().includes(keyword) ||
      code.toLowerCase().includes(keyword)
    ) {
      matchedCodes.push(code);
    }
  });

  // 记录匹配及其祖先路径
  const visibleCodes = new Set();
  matchedCodes.forEach(code => {
    let current = code;
    while (current) {
      visibleCodes.add(current);
      current = parentMap.get(current);
    }
  });

  function filterTree(nodes) {
    return nodes
      .filter(node => visibleCodes.has(node.code))
      .map(node => ({
        ...node,
        children: node.children ? filterTree(node.children) : undefined
      }));
  }

  treeData.value = filterTree(rawTree.value);

  // 自动展开路径
  nextTick(() => {
    matchedCodes.forEach(code => {
      let current = code;
      while (current) {
        treeRef.value?.expandNode?.(nodeMap.get(current));
        current = parentMap.get(current);
      }
    });
  });
}
</script>

<style scoped>
.hs-tree-wrapper {
  display: flex;
  flex-direction: column;
}
.filter-input {
  margin-bottom: 12px;
  width: 100%;
}
.hs-tree {
  flex: 1;
  max-height: 600px;
  overflow: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
}
</style>
